//商品数组
let products = [
  {
    id: 1003,
    name: "我和你",
    picture: "./image/book22.png",
    price: 28.9,
    num: 0,
    // singlePrice: 0,
    state: false, //选中状态
  },
  {
    id: 1004,
    name: "你和他",
    picture: "./image/book22.png",
    price: 28.9,
    num: 0,
    // singlePrice: 0,
    state: false,
  },
  {
    id: 1005,
    name: "他和她",
    picture: "./image/book22.png",
    price: 28.9,
    num: 0,
  
    state: false,
  },
  {
    id: 1006,
    name: "她和它",
    picture: "./image/book22.png",
    price: 28.9,
    num: 0,
  
    state: false,
  },
];
//单选状态
/**
 * 显示所有商品
 *  思路: 根据商品数组数据，生成商品列表html节点字符串,将商品列表节点字符串作为内容赋值给table父节点
 */
let Allcheked = false;
function showProductList() {
  let str = `  
  <tr>
  <th><input type="checkbox" name="" id="" class="checkbox-all" ${
    Allcheked == true ? "checked" : ""
  }>全选</th>
  <th>商品编号</th>
  <th>商品图片</th>
  <th>商品信息</th>
  <th>单价</th>
  <th>数量</th>
  <th>总价</th>
  <th>操作</th>
</tr>
  `;
  products.forEach((item,index) => {
    str += `
     <tr>
     <td><input type="checkbox" name="" id="" class="checkbox-item" ${
       item.state == true ? "checked" : ""
     } ></td>
     <td>${item.id}</td>
     <td><img src="${item.picture}"></td>
     <td>${item.name}</td>
     <td class="singer">￥${item.price}</td>
     <td><input type="button" name="minus" value="-" class="minus" ${item.num>0 ?'':'disabled'} >
         <input type="text" name="amount" value="${
           item.num
         }"  class="amount" >
         <input type="button" name="plus" value="+"   class="plus"></td>
     <td  class="all">￥${(item.price * item.num).toFixed(2)}</td>
     <td><a href="#"  class="a">移入收藏</a><br><a href="#"class="del" date-index='${index}'>删除</a></td>
 </tr>  
     `;
  });
  $("table").html(str);
}

/**
 * 添加商品
 *   思路: 构造商品购物项数据，将商品购物项数据添加到商品数组
 *      1. 构造商品购物项数据
 *          1.1 从商品表单获取数据
 *          1.2 生成一条商品购物项数据
 *            let product = {id:3, name:'javascript高级编程', picture:'./image/book22.png', price:58.90, num:0, singlePrice:0},
 *      2. 将商品购物项数据添加到商品数组
 *          products.push(product)
 */
function addProduct() {
  $("#addbookbtn").on("click", function () {
    let bookname = $('input[name="bookname"]').val();
    let bookprice = $('input[name="bookprice"]').val();
    let bookpicture = $('input[name="bookpicture"]').val();
    console.log('bookname',bookname,'bookprice ',bookprice ,'bookpicture',bookpicture)
    if (bookname == "" || bookpicture == "" ) {
      alert("请输入完整信息");
    } 
    else if(isNaN(bookprice)|| bookprice == ""){  alert('请输入数字')}
    else {
      let obj = {
        id: getRandom(10, 10000),
        name:  $('input[name="bookname"]').val(),
        picture:$('input[name="bookpicture"]').val(),
        price: $('input[name="bookprice"]').val(),
        num: 0,
        state: false,
      };
      products.push(obj);
      console.log(products)
      //清空输入框
      $('input[name="bookname"]').val("");
      $('input[name="bookprice"]').val("");
      $('input[name="bookpicture"]').val("");
      showProductList()
    }
  });
}

/**
 * 删除商品
 *  思路: 删除数组中指的数据.
 *      1. 找到要删除商品在数组中的索引号
 *         1.1 给删除节点添加一个自定义属性，属性值是当前商品的索引号
 *         1.2 找商品唯一id, 根据id在数组中确定该商品的索引号
 *      2. products.splice(index,1)
 */
function  onProduct(){
  console.log($('.del'))
  $('table').on('click','.del',function(){
    let id=$(this).parent().parent().children().next().html()
    // let id=$(this).parent().parent().children().eq(1).html()
    let indexE=products.findIndex(item =>item.id==id)
     products.splice(indexE,1)
    showProductList(products)
    totalPrice()
  })
}
//增删查改
function getNum(){
  //加号
  $('table').on('click','.plus',function(){
    let id=$(this).parent().parent().children().next().html()
    let product=products.find(item=>item.id==id)
      console.log(product)
      product.num++
    showProductList()
    totalPrice()
  })
 //减号
 $('table').on('click','.minus',function(){
  let id=$(this).parent().parent().children().next().html()
  let product=products.find(item=>item.id==id)
    console.log(product)
    product.num--
  showProductList()
  totalPrice()
})
//全选
$('table').on('click','.checkbox-all',function(){
  Allcheked=!Allcheked
  console.log( Allcheked)
  products.forEach(item=>{
    if(Allcheked){
      item.state=true
    }else{
      item.state=false
    }
  })
  showProductList()
})
$('table').on('click','.checkbox-item',function(){
let id=$(this).parent().next().html()
let product=products.find(item=>item.id==id)
console.log('先',product.state)
product.state=!product.state
console.log('单',product.state)
console.log('后',products)
 Allcheked = products.every(item=>item.state==true)
 console.log('quan',Allcheked)
showProductList()
totalPrice()
})
}
getNum()


/**
 * 计算所有商品总价
 *  思路: 遍历数组，将singleprice累加
 */
function totalPrice() {
  let all=products.reduce((s,item)=>{
    return   s+=Number((item.num*item.price).toFixed(2))
  },0)
  console.log(products)
$('.book-list span').html(all)

}

/**
 * 生成x~y之间的随机数
 * @param {*} x
 * @param {*} y
 * @returns
 */
function getRandom(x, y) {
  // 保证m是最小值,n是最大值
  var n = Math.max(x, y); // 80
  var m = Math.min(x, y); // 50
  return Math.floor(Math.random() * (n - m)) + m;
}
showProductList();
addProduct();
onProduct();
